package com.zhiyou100.xml.jsoup;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;
import java.net.URL;

public class Demo3 {

    public static void main(String[] args) throws IOException {

        /*获取Element对象
                * getElementById (String id)：根据id属性值获取唯一的element对象
                * getElementsByTag (String tagName)：根据标签名称获取元素对象集合
                * getElementsByAttribute (String key)：根据属性名称获取元素对象集合
                * getElementsByAttributeValue (String key, String value)：根据对应的属性名和属性值获取元素对象集合
        */
        //获取一个类加载器
        ClassLoader loader = Demo1.class.getClassLoader();
        //加载xml文件，将其转换为一个URL资源
        URL resource = loader.getResource("test.xml");
        //获取资源路劲
        String path = resource.getPath();
        System.out.println("path = " + path);
        //利用jsoup加载配置文件
        Document document = Jsoup.parse(new File(path), "UTF-8");
        //根据元素的id获取元素
        Element element = document.getElementById("001");
        System.out.println("element = " + element);
        //根据元素的属性获取元素
        Elements elements = document.getElementsByAttribute("name");
        for (Element element1 : elements) {
            System.out.println("element1.text() = " + element1.text());
            //获取属性值
            String id = element1.attr("id");
            System.out.println("id = " + id);
        }
        //根据属性key与value获取
        Elements elements1 = document.getElementsByAttributeValue("name", "user2");
        System.out.println("elements1.text() = " + elements1.text());

    }

}
